package cn.tedu.rabbitmq.rpc;

import com.rabbitmq.client.*;
import com.rabbitmq.client.AMQP.BasicProperties;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class RPCServer {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1.接受客户端发送的调用信息(正整数n)
        //2.执行算法，求第n个斐波那契数
        //3.向客户端发送计算结果
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("127.0.0.1"); //设置主机
        cf.setPort(5672); //客户端连接服务端的端口号，默认是5672，可以省略
        cf.setUsername("guest");
        cf.setPassword("guest");
        Connection nc = cf.newConnection();
        Channel cc = nc.createChannel();
        cc.queueDeclare("rpc_queue",false,false,false,null);
        DeliverCallback deliverCallback = new DeliverCallback() {
            @Override
            public void handle(String s, Delivery delivery) throws IOException {
                //从Delivery中取出消息n  返回队列队列名 关联id
                String n = new String(delivery.getBody()); //n
                String replyTo = delivery.getProperties().getReplyTo();//返回队列的队列名
                String cid = delivery.getProperties().getCorrelationId();//关联id
                BasicProperties props = new BasicProperties.Builder().correlationId(cid).build();
                //执行斐波那契数
                long fbnqs = fbnqs(Integer.parseInt(n));
                //把计算结果发送给返回队列
                cc.basicPublish("",replyTo,props,(fbnqs+"").getBytes());
            }
        };
        CancelCallback cancelCallback = new CancelCallback() {
            @Override
            public void handle(String s) throws IOException {
            }
        };
        cc.basicConsume("rpc_queue",true,deliverCallback,cancelCallback);
    }

    //服务：接受一个整数值n，求第n个斐波那契数
    //前两项都是1，从第三项开始是前两项之和
    //1 1 2 3 5 8 13 21 34 55 89 .......
    //递归求斐波那契数，递归效率低，可以用来模拟服务器的耗时运算
    static long fbnqs(int n){
        //递归必须有结束条件
        if(n==1 || n==2)
            return 1;
        return fbnqs(n-1)+fbnqs(n-2);
    }
}
